import {
  BadRequestException,
  Injectable,
  NestMiddleware,
} from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';

@Injectable()
export class CaptchaMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    const captcha = svgCaptcha.createMathExpr({
      size: 5, // 长度
      ignoreChars: 'il1', // 排除的字符
      noise: 2, // 干扰线条数
      color: true, // 五颜六色
    });
    req.session.captchaCode = captcha.text; // 把验证码的文本存到session，登录的时候校验与用户输入是否一致
    // 将 SVG 转换为 Base64
    const svg = captcha.data; // SVG 字符串
    const base64Image = Buffer.from(svg).toString('base64');
    const base64DataUrl = `data:image/svg+xml;base64,${base64Image}`;

    req.captcha = {
      captchaBase64: base64DataUrl,
      captchaKey: captcha.text,
    };
    next();
  }
}

// 校验图形验证码（原始的函数式中间件）
export const visCaptcha = (req, res, next) => {
  // 校验 req.session.captcha 是否等于 req.body.captcha

  if (req.session.captchaCode != req.body?.captchaCode) {
    req.session.captchaCode = '';
    throw new BadRequestException('图形验证码校验失败');
  }
  req.session.captchaCode = '';
  next();
};
